/*========= Starting function =========*/
$(function() {
    $(document).ready(function() {
        user.init();
    });
    
});

var user = (function() {

    /*========================================================================================
     *ADD NEW USER BLOCK
     *========================================================================================
     */
    function addUser_validate() {
        var error = true,
            uname = $('#username').val(),
            pass = $('#password').val(),
            repass = $('#repassword').val(),
            email = $('#email').val();

        if (!/^[a-zA-Z0-9._-]{3,16}$/i.test(uname)) {
            $('#username').addClass('error');
            error = false;
        }

        if (!/^[A-Za-z0-9!@#$%^&*()_]{3,16}$/i.test(pass)) {
            $('#password').addClass('error');
            error = false;
        }

        if (repass != pass) {
            $('#repassword').addClass('error');
            error = false;
        }

        if (!/^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]{2,5}$/i.test(email)) {
            $('#email').addClass('error');
            error = false;
        }

        return error;
    }

    function userForm_reset(flag) {
        $('input[type=text]').removeClass('error');
        $('input[type=password]').removeClass('error');
        $('#err_msg').hide().find('.alert').removeClass('alert-success').addClass('alert-error');
        if (flag) {
            $('input[type=text]').val('');
            $('input[type=password]').val('');
            $('#err_msg .alert').html('');
        }
    }

    function addUser_handler() {
        //submit new user 
        $('#add_new_submit').click(function() {
            userForm_reset();
            if (addUser_validate()) {
                var url = '/user/ajax_add_new_user';
                $.ajax({
                    type: "POST",
                    url: url,
                    data: {
                        fname: $('#f_name').val(),
                        lname: $('#l_name').val(),
                        username: $('#username').val(),
                        password: $('#password').val(),
                        email: $('#email').val(),
                        role: $('input:radio[name=role]:checked').val()
                    },
                    dataType: 'json',
                    success: function(resp) {
                        if (resp.err != 0) {
                            for (var i in resp.msg)
                                $('#' + i).addClass('error');

                            var msg,
                                err = resp.err;
                            switch (err) {
                                case -2:
                                    msg = 'Username exist, please choise another one.';
                                    break;
                                case -3:
                                    msg = 'Email exist, please choise another one.';
                                    break;
                                default:
                                    msg = 'Something wrong, please check again.';
                            }
                            $('#user_add_new #err_msg').show().find('.alert').removeClass('alert-success').addClass('alert-error').html(msg);
                        } else if (resp.err == 0) {
                            $('#user_add_new #err_msg').show().find('.alert').removeClass('alert-error').addClass('alert-success').html('Successfull.');
                            window.location.href = '/user/edit/' + resp.id;
                        }
                    }
                });
            } else {
                $('#user_add_new #err_msg').show().find('.alert').removeClass('alert-success').addClass('alert-error').html('Something wrong, please check again.');
            }
            return false;
        });

        //reset form
        $('#add_new_reset').click(function() {
            userForm_reset(true);
            return false;
        });
    }

    /*========================================================================================
     *EDIT USER BLOCK
     *========================================================================================
     */
    function editUser_validate() {
        var error = true,
            uname = $('#username').val(),
            newpass = $('#newpassword').val(),
            oldpass = $('#oldpassword').val(),
            repass = $('#repassword').val(),
            email = $('#email').val();

        if (!/^[a-zA-Z0-9._-]{3,16}$/i.test(uname)) {
            $('#username').addClass('error');
            error = false;
        }

        if (newpass != '') {
            if (oldpass == '') {
                $('#oldpassword').addClass('error');
                error = false;
            } else if (!/^[A-Za-z0-9!@#$%^&*()_]{3,16}$/i.test(newpass)) {
                $('#newpassword').addClass('error');
                error = false;
            }
        }

        if (repass != newpass) {
            $('#repassword').addClass('error');
            error = false;
        }

        if (!/^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]{2,5}$/i.test(email)) {
            $('#email').addClass('error');
            error = false;
        }

        return error;
    }

    function editUser_handler() {
        // Edit user infor
        $('#edit_user_submit').click(function() {
            userForm_reset();
            if (editUser_validate()) {
                var url = '/user/ajax_edit_user'
                $.ajax({
                    type: "POST",
                    url: url,
                    data: {
                        id: $('#user_id').val(),
                        fname: $('#f_name').val(),
                        lname: $('#l_name').val(),
                        username: $('#username').val(),
                        oldpassword: $('#oldpassword').val(),
                        newpassword: $('#newpassword').val(),
                        email: $('#email').val(),
                        role: $('input:radio[name=role]:checked').val()
                    },
                    dataType: 'json',
                    success: function(resp) {
                        if (resp.err == 0) {
                            $('#user_edit #err_msg').show().find('.alert').removeClass('alert-error').addClass('alert-success').html('Successfull.');
                        } else if (resp.err != 0) {
                            for (var i in resp.msg)
                                $('#' + i).addClass('error');
                            var msg, err = resp.err;
                            switch (err) {
                                case -2:
                                    msg = 'Username exist, please choise another one.';
                                    break;
                                case -3:
                                    msg = 'Email exist, please choise another one.';
                                    break;
                                case -4:
                                    msg = 'Old password incorrect, please check agian.';
                                    break;
                                default:
                                    msg = 'Something wrong, please check again.';
                            }
                            $('#user_edit #err_msg').show().find('.alert').removeClass('alert-success').addClass('alert-error').html(msg);
                        }
                    }
                });
            } else {
                $('#user_edit #err_msg').show().find('.alert').removeClass('alert-success').addClass('alert-error').html('Something wrong, please check again.');
            }
            return false;
        });

        // Edit User Status
        $('input:radio[name=status]').click(function() {
            var val = $(this).val(),
                uid = $('#user_edit #user_id').val(),
                status = val == 1 ? 'Active' : 'Deactive',
                info = '<br/><p>Are you sure to <span class="text-error">' + status + '</span> this user?<br/><br/>';
            showConfirm({
                title: 'User Status',
                msg: info,
                noBt: 'No, not now.',
                yesBt: 'Yes, Process it.',
                onYes: function() {
                    var url = '/user/ajax_edit_user_status';
                    $.ajax({type: "POST", url: url, data: {uid: uid, status: val}, dataType: 'json',
                        success: function(resp) {
                            if (resp.err != 0)
                                showAlert('Something wrong, please try again later.');
                        }
                    });
                }
            })
        });

        // Remove User
        $('.profileRemoveUser').click(function() {
            var uid = $(this).attr('id').replace('removeUser_', ''),
                uname = $(this).attr('rel'),
                info = '<br/><p>Are you sure to delete the user with username <span class="text-error">' + uname + '</span>?<br/><br/>'
            showConfirm({
                title: 'Delete user',
                msg: info,
                warning: '<p class="text-warning" align="left">Please understand that this action cannot be reverted. </p>',
                noBt: 'No, not now.',
                yesBt: 'Delete.',
                onYes: function() {
                    var url = '/user/ajax_remove_user';
                    $.ajax({type: "POST", url: url, data: {uid: uid}, dataType: 'json',
                        success: function(resp) {
                            if (resp.err != 0)
                                showAlert('Something wrong, please try again later.');
                            else if (resp.err == 0) {
                                window.location = '/user';
                            }
                        }
                    });
                }
            });
            return false;
        })
    }

    /*========================================================================================
     *ALL USER BLOCK
     *========================================================================================
     */

    function allUser_handler() {
        $('#list_all_user .removeUser').click(function() {
            var uid = $(this).attr('id').replace('removeUser_', ''),
                uname = $(this).attr('rel'),
                info = '<br/><p>Are you sure to delete the user with username <span class="text-error">' + uname + '</span>?<br/><br/>'
            showConfirm({
                title: 'Delete user',
                msg: info,
                warning: '<p class="text-warning" align="left">Please understand that this action cannot be reverted. </p>',
                noBt: 'No, not now.',
                yesBt: 'Delete.',
                onYes: function() {
                    var url = '/user/ajax_remove_user';
                    $.ajax({type: "POST", url: url, data: {uid: uid}, dataType: 'json',
                        success: function(resp) {
                            if (resp.err != 0)
                                showAlert('Something wrong, please try again later.');
                            else if (resp.err == 0) {
                                $('tr#userRow_' + uid).remove();
                            }
                        }
                    });
                }
            });
            return false;
        })
    }


    /*========================================================================================
     *RETURN OBJECT USER
     *========================================================================================
     */
    return {
        init: function() {
            addUser_handler();
            editUser_handler();
            allUser_handler();
        }
    };

})();